<template>
  <div style="background-color: #B10A11; color: white; padding: 20px; font-weight: bold; font-size: 60px;">
    PROCESS MAPPING
  </div>
  <div ref="chartDom" class="h-full w-full "></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import * as echarts from 'echarts';
import workstation from '@/api/manu/workstation';

interface coordiante {
  id: number;
  x: number;
  y: number;
}

const routerParam = useRoute().params.line;
const router = Array.isArray(routerParam) ? routerParam[0].toUpperCase() : routerParam.toUpperCase();

// 创建一个响应式引用来保存DOM元素
const chartDom = ref(null);
let chartInstance: echarts.ECharts | null = null;
const step = ref(45);

const coordinateList = [
  {
    "id":1,
    "routename":"HM",
    "stationid":1,
    "x":1,
    "y":7
  },
  {
    "id":2,
    "routename":"HM",
    "stationid":2,
    "x":2,
    "y":6
  },
  {
    "id":3,
    "routename":"HM",
    "stationid":3,
    "x":2,
    "y":5
  },
  {
    "id":4,
    "routename":"HM",
    "stationid":4,
    "x":2,
    "y":4
  },
  {
    "id":5,
    "routename":"HM",
    "stationid":5,
    "x":3,
    "y":7
  },
  {
    "id":6,
    "routename":"HM",
    "stationid":6,
    "x":4,
    "y":7
  },
  {
    "id":7,
    "routename":"HM",
    "stationid":7,
    "x":5,
    "y":7
  },
  {
    "id":8,
    "routename":"HM",
    "stationid":8,
    "x":6,
    "y":7
  },
  {
    "id":9,
    "routename":"HM",
    "stationid":9,
    "x":6,
    "y":2
  },
  {
    "id":10,
    "routename":"HM",
    "stationid":10,
    "x":5,
    "y":2
  },
  {
    "id":11,
    "routename":"HM",
    "stationid":11,
    "x":4,
    "y":2
  },
  {
    "id":12,
    "routename":"HM",
    "stationid":12,
    "x":3,
    "y":2
  },
  {
    "id":13,
    "routename":"HM",
    "stationid":13,
    "x":2,
    "y":2
  },
  {
    "id":14,
    "routename":"HM",
    "stationid":14,
    "x":1,
    "y":2
  },
  {
    "id":15,
    "routename":"HM",
    "stationid":15,
    "x":1,
    "y":1
  },
  {
    "id":16,
    "routename":"HM",
    "stationid":16,
    "x":2,
    "y":1
  },
  {
    "id":17,
    "routename":"BV",
    "stationid":18,
    "x":1,
    "y":7
  },
  {
    "id":18,
    "routename":"BV",
    "stationid":19,
    "x":2,
    "y":5
  },
  {
    "id":19,
    "routename":"BV",
    "stationid":20,
    "x":2,
    "y":3
  },
  {
    "id":20,
    "routename":"BV",
    "stationid":21,
    "x":3,
    "y":7
  },
  {
    "id":21,
    "routename":"BV",
    "stationid":22,
    "x":4,
    "y":7
  },
  {
    "id":22,
    "routename":"BV",
    "stationid":23,
    "x":5,
    "y":7
  },
  {
    "id":23,
    "routename":"BV",
    "stationid":24,
    "x":6,
    "y":7
  },
  {
    "id":24,
    "routename":"BV",
    "stationid":25,
    "x":6,
    "y":5
  },
  {
    "id":25,
    "routename":"BV",
    "stationid":26,
    "x":6,
    "y":3
  },
  {
    "id":26,
    "routename":"BV",
    "stationid":27,
    "x":6,
    "y":1
  },
  {
    "id":27,
    "routename":"BV",
    "stationid":28,
    "x":5,
    "y":1
  },
  {
    "id":28,
    "routename":"BV",
    "stationid":29,
    "x":4,
    "y":1
  }
]
const pointColor = ref('#ccc');

const getCoordinate = (route: string) => {
  let coordinates = coordinateList.filter((item) => item.routename === route);
  let dataSet: { name: number; value: number[]; itemStyle: { color: string } }[] = []
  coordinates.forEach((item) => {
    dataSet.push({
      name: item.stationid,
      value: [item.x * step.value, item.y * step.value],
      itemStyle: { color: pointColor.value }
    })
  })
  return dataSet;
}

const getRouteByStation = (pointList: number[], color: string) => {
  let route = [];
  let beginCoord = coordinateList.find((item) => item.stationid === pointList[0]);
  if (beginCoord) {
    route.push([beginCoord.x * step.value, beginCoord.y * step.value]);
  }
  for (let i = 0; i < pointList.length - 1; i++) {
    let start = pointList[i];
    let end = pointList[i + 1];
    let startCoord = coordinateList.find((item) => item.stationid === start);
    let endCoord = coordinateList.find((item) => item.stationid === end);
    if (startCoord && endCoord && startCoord.y != endCoord.y) {
      route.push([startCoord.x * step.value, endCoord.y * step.value]);
    }
    if (startCoord && endCoord && startCoord.x != endCoord.x) {
      route.push([endCoord.x * step.value, endCoord.y * step.value]);
    }
  }
  return {
    coords: route,
    lineStyle: {
      normal: {
        opacity: 0.5, //线条透明度
        color: color,
        width: 0,
        curveness: 0, //动画线路的曲度
      }
    },
  }
}

const getWorkStationInfoById = (id: any) => {
  let ws = workstation.find(item => item.id == id)
  return ws!.name
}

const buildLabelByStationId = (id: any) => {
  let ws = workstation.find(item => item.id == id)
  // '{name|name} \n {mode|M}   {ct|39s}   {mp|L3}  {trace|}  {kc|}  {cc|}'
  let label: string = '';
  let name = ws!.name;
  let mode = ws?.mode[0];
  let ct = ws?.ct;
  let mp = '';
  if (ws?.mplevel) {
    mp = 'L' + ws?.mplevel;
  }
  let trace = ws?.traceability;
  let kc = ws?.KC;
  let cc = ws?.CC;
  label = '{name|' + name + '} \n {mode|' + mode + '}   {ct|' + ct + 's}   '
  if (mp.length > 0) {
    label += '{mp|' + mp + '}'
  }
  if (trace) {
    label += '  {trace|}'
  }
  if (kc) {
    label += '  {kc|}'
  }
  if (cc) {
    label += '  {cc|}'
  }
  label += '\n {description|' + ws?.description + '}'
  return label
}

const getRouteByMappingName =(route:string)=>{
  if(route === 'HM'){
    return [getRouteByStation([1, 2, 5], '#ffaaaa'), getRouteByStation([1, 3, 5], '#ffaaaa'), getRouteByStation([1, 4, 5], '#ffaaaa'), getRouteByStation([1, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], '#35c2ff')]  
  } else {
    return [getRouteByStation([18, 19, 21], '#ffaaaa'), getRouteByStation([18, 20, 21], '#ffaaaa'), getRouteByStation([18,21,22,23,24,25,26,27,28,29], '#35c2ff')]
  }
}



// 初始化ECharts实例并设置配置项（这里以折线图为例，但可灵活替换）
onMounted(async () => {
  await nextTick(); // 确保DOM已经渲染完成
  chartInstance = echarts.init(chartDom.value);
  const option = {

    grid: {
      left: '5%',
      right: '10%',
      top: '-5%',
      bottom: '-5%',
      backgroundColor: 'rgb(128, 128, 128)',
    },
    xAxis: {
      type: 'value',
      show: false,
      boundaryGap: false,
    },
    yAxis: {
      type: 'value',
      show: false,
      boundaryGap: false,
    },
    series: [
      {
        type: 'scatter',
        data: getCoordinate(router),
        symbol: function (value: number, params: { data: { name: string } }) {
          let url = 'https://wine-plus.oss-cn-beijing.aliyuncs.com/processmapping/ws/' + params.data.name + '.png'
          return 'image://' + url
        },
        symbolSize: 120,
        label: {
          show: true,
          normal: {
            show: true,
            position: 'left',
            formatter: function (params: any) {
              return buildLabelByStationId(params.data.name)
            },
            backgroundColor: "#eee",
            borderRadius: 10,
            color: "#000",
            shadowBlur: 3,
            shadowColor: "#888",
            lineHeight: 25,
            width: 200,
            height: 100,
            padding: [10, 0, 10, 10],
            rich: {
              name: {
                align: 'left',
                verticalAlign: 'top',
                fontWeight: 'bold',
                fontSize: 20,
              },
              mode: {
                color: '#FFFFFF',
                fontWeight: 'bold',
                backgroundColor: '#0E95DB',
                align: 'left',
                verticalAlign: 'middle',
                lineHeight: 30,
                borderColor: '#0E95DB',
                borderWidth: 2,
                borderRadius: 10,
                height: 30,
              },
              ct: {
                color: '#FFFFFF',
                backgroundColor: '#FF00FF',
                align: 'left',
                verticalAlign: 'middle',
                lineHeight: 30,
                borderColor: '#FF00FF',
                borderWidth: 2,
                borderRadius: 10,
                height: 30,
              },
              mp: {
                color: '#FFFFFF',
                backgroundColor: '#3333FF',
                align: 'left',
                verticalAlign: 'middle',
                lineHeight: 30,
                borderColor: '#000000',
                borderWidth: 1,
                height: 30,
                fontsize: 30,
              },
              trace: {
                backgroundColor: { image: 'https://wine-plus.oss-cn-beijing.aliyuncs.com/processmapping/icon/trace.png' },
                align: 'left',
                verticalAlign: 'middle',
                lineHeight: 30,
                fontsize: 40,
                height: 30,
              },
              kc: {
                backgroundColor: { image: 'https://wine-plus.oss-cn-beijing.aliyuncs.com/processmapping/icon/kc.png' },
                align: 'left',
                verticalAlign: 'middle',
                lineHeight: 30,
                fontsize: 40,
                height: 30,
              },
              cc: {
                backgroundColor: { image: 'https://wine-plus.oss-cn-beijing.aliyuncs.com/processmapping/icon/cc.png' },
                align: 'left',
                verticalAlign: 'middle',
                lineHeight: 30,
                fontsize: 40,
                height: 30,
              },
              description: {
                align: 'left',
                fontWeight: 'bold',
                fontSize: 12,
                verticalAlign: 'bottom',
              },

            },
          },

        },
      },
      {
        type: 'lines',
        coordinateSystem: 'cartesian2d',
        polyline: true,
        effect: {
          show: true,
          period: 3,
          trailLength: 0.71,
          symbolSize: 13,
          symbol: "circle",
          loop: true,
          constantSpeed: 300,
        },
        data: getRouteByMappingName(router),
      },
    ],
    animationDuration: 1000,
  };

  chartInstance.setOption(option);
});

// 销毁ECharts实例
onUnmounted(() => {
  if (chartInstance != null && chartInstance.dispose) {
    chartInstance.dispose();
  }
  window.removeEventListener('resize', () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  });
});
</script>

<style scoped>
/* 添加一些CSS样式来美化图表容器（可选） */
</style>
